<template>
  <div class="app-container">
    <div class="btns" v-show="isQuery === false">
      <el-button-group>
        <el-button class="select-file-button">
          <input type="file" id="fileInput" :multiple="multiple" class="select-file-input" οnclick="f.outerHTML=f.outerHTML" @change="handleFileChange" />
        </el-button>
        <el-button type="primary" @click="doFileUpload" style="width:100px"><i class="el-icon-upload"></i>点击上传</el-button>
        <el-button type="primary" @click="doRefresh" style="margin-left:5px;width:100px"><i class="el-icon-refresh"></i>刷新</el-button>
      </el-button-group>
      <slot name="header"></slot>
    </div>
    <el-table class="tl-table" ref="mainTable" :height="isSubPage ? '300px' : tableHeight" resizable-key="tableHeight" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClick" @row-click="doRowClick" row-key="id" border fit :row-class-name="doChangeRowClassName">
      <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
      <el-table-column prop="name" label="文件名" min-width="250px" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="filesize" label="文件大小" width="100px" align="center" :formatter="formatFileSize"></el-table-column>
      <el-table-column prop="type" label="文件类型" width="100px"></el-table-column>
      <el-table-column prop="uploadusername" label="上传人" width="100px" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="dispuploadstate" label="状态" width="100px"></el-table-column>
      <el-table-column prop="progress" label="进度" width="150px">
        <template slot-scope="scope">
          <el-progress :show-text="true" :percentage="scope.row.progress"></el-progress>
        </template>
      </el-table-column>
      <el-table-column prop="recordtime" label="上传日期" width="180px" align="center" sortable="custom" sort-by="recordtime"></el-table-column>
      <el-table-column label="操作" width="200px" align="center" v-slot="scope" fixed="right">
        <!--<el-upload v-show="scope.row.id !== undefined" v-if="isQuery === false" style="display:inline-block;margin-right:10px" ref="signleUploadRef" width="80px" :http-request="uploadSignleFile" :auto-upload="true" action :data="scope.row" :show-file-list="false">
          <el-button type="text" icon="el-icon-upload2" class="filter-item">续传</el-button>
        </el-upload>-->
        <el-button v-if="isQuery === false" type="text" icon="el-icon-delete" @click="doDelete(scope)">删除</el-button>
        <el-button type="text" icon="el-icon-video-play" @click="doPlay(scope.row.id)">播放</el-button>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="playAudioVisible" class="audio-dialog" :title="this.audioName" :close-on-click-modal="false" style="" @close="playClose('audio')" :modal="false" :modal-append-to-body="false" :append-to-body="true">
      <tl-play-audio ref="playAudioForm"></tl-play-audio>
    </el-dialog>
    <el-dialog :visible.sync="playVideoVisible" title="播放" class="tl-dialog" :close-on-click-modal="false" style="" @close="playClose('video')" :modal="false" :modal-append-to-body="false" :append-to-body="true">
      <tl-play-video ref="playVideoForm"></tl-play-video>
    </el-dialog>
  </div>
</template>
<script>
import axios from '@tapui/utils/request'
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
/** 子组件 */
import tlPlayAudio from '../audioPlay/playAudioHls'
import tlPlayVideo from '../audioPlay/playVideoHls'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import SparkMD5 from 'spark-md5'
const BLOCK_SIZE = 3 * 1024 * 1024 // 块大小
const MIN_BLOCK_SIZE = 0 // 最小块大小
// 所有文件状态
const fileStatus = {
  wait: 'wait',
  md5: 'md5',
  uploading: 'uploading',
  uploadFinish: 'uploadFinish',
  merge: 'merge',
  password: 'password',
  splice: 'splice',
  error: 'error',
  finish: 'finish',
  delete: 'delete'
}
// 单个文件的状态 对应描述
const fileStatusStr = {
  wait: '待上传',
  md5: '计算中',
  uploading: '上传中',
  uploadFinish: '上传结束',
  merge: '合并',
  password: '加密',
  splice: '切片',
  error: '失败',
  finish: '已完成',
  delete: '删除'
}
// 文件类型
const fileType = {
  audio: 'audio',
  video: 'video'
}
export default {
  name: 'fileManage',
  mixins: [mixin_list],
  components: { tlPlayVideo, tlPlayAudio },
  data: () => ({
    description: '文件管理-列表查询',
    urlPrefix: '/meet/fileManage/',
    // 选择的文件
    selectFiles: [],
    // 正在上传文件队列
    uploadFiles: [],
    data: [],
    url: {
      uploadFileBlock: '/meet/fileManage/uploadFileBlock',
      mergeFileBlocks: '/meet/fileManage/mergeFileBlocks',
      queryAlreadyUploadBlocksNum: '/meet/fileManage/queryUploadBlocks',
      load: '/meet/fileManage/load',
      getBlobSrc: '/play111/getBlobSrc',
      m3u8Url: '/play111/output.m3u8'
    },
    tableData: [],
    // mixin_list中reduceHeight的高度 + 自定义文件上传div的高度
    reduceHeight: 134 + 45,
    // 排序参数
    sorterInfo: {
      sidx: 'recordtime',
      sord: 'desc'
    },
    playAudioVisible: false,
    playVideoVisible: false,
    audioName: '播放',
    index: 0,
    // 分页信息
    pageInfo: {
      currentPage: 1, // 当前页面
      pageSize: 1000, // 每页记录数
      pageSizes: ['1000'],
      totalCount: 0 // 总数
    },
    // 前一个会议的id
    oldSourceId: 0
  }),
  props: {
    // 文件个数
    limit: {
      type: Number,
      default: 5
    },
    // 总文件个数
    limitSum: {
      type: Number,
      default: 1000
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 上传文件类型
    limitType: {
      type: String,
      default: 'MP3,AAC'
    },
    isSubPage: {
      type: Boolean,
      default: false
    },
    // 是否查询页面
    isQuery: {
      type: Boolean,
      default: true
    },
    sourceType: {
      type: String,
      default: ''
    },
    sourceId: {
      type: [Number, String],
      default: ''
    }
  },
  methods: {
    /** 加载数据之前 */
    beforeLoadData() {
      if (this.isSubPage) {
        this.queryParam.qry_sourceid = this.sourceId
      }
      this.queryParam = {
        ...this.queryParam,
        qry_sourcetype: this.sourceType
      }
      return true
    },
    /** 选择上传文件*/
    handleFileChange(e) {
      const files = e.target.files
      if (!files) return
      // 类型判断
      const postFiles = Array.prototype.slice.call(files)
      let isRight = true
      for (let item of postFiles) {
        if (this.limitType) {
          let fileType = this.getFileExt(item.name)
          for (let type of this.limitType.split(';')) {
            if (type.toLowerCase().indexOf(fileType.toLowerCase()) === -1) {
              isRight = false
              break
            }
          }
        }
      }
      if (!isRight) {
        document.getElementById('fileInput').value = ''
        this.$tap.alert(`上传文件只能是 ${this.limitType}格式!`, 'warning')
        return
      }
      // 判断文件选择的个数
      if (this.limit && files.length > this.limit) {
        document.getElementById('fileInput').value = ''
        this.$tap.alert('文件最多支持选择' + this.limit + '个', 'warning')
        return
      }
      if (this.limit && files.length + this.datas.length > this.limitSum) {
        document.getElementById('fileInput').value = ''
        this.$tap.alert('文件总共允许最多上传' + this.limitSum + '个', 'warning')
        return
      }
      postFiles.forEach(item => {
        this.initUploadFile(item)
      })
    },
    /** 初始化上传文件 */
    initUploadFile(fileObject) {
      var file = {}
      file.fileObject = fileObject
      file.filename = fileObject.name
      file.name = fileObject.name
      file.uploadstate = fileStatus.wait
      file.blockList = []
      file.progress = 0
      file.filesize = fileObject.size
      file.blocksize = BLOCK_SIZE
      file.type = this.getFileExt(fileObject.name)
      file.recordtime = ''
      file.id = this.index--
      file.alreadyuploadblocksnum = []
      file.sourceid = this.sourceId
      file.sourcetype = this.sourceType
      this.formatFileState(file, fileStatus.wait)
      this.selectFiles.push(file)
      this.datas = [file, ...this.datas]
    },
    /** 进行文件上传 */
    doFileUpload() {
      document.getElementById('fileInput').value = ''
      if (!this.selectFiles) return
      let arr = []
      for (let element of this.selectFiles) {
        // 设置md5状态
        this.formatFileState(element, fileStatus.md5)
        arr.push(this.computeMD5(element.fileObject))
      }
      // 计算选择文件的md5
      Promise.all(arr).then(results => {
        results.forEach((md5, index) => {
          this.selectFiles[index].identifier = md5
          this.selectFiles[index].filemd5 = md5
        })
        // 比较列表清空相同的
        this.doCompare()
        for (let element of this.selectFiles) {
          // 添加到发送队列进行发送
          this.addUploadList(element)
        }
        this.selectFiles = []
      })
    },
    /** 对比列表文件,删除重复文件 */
    doCompare() {
      let isExistSame = false
      // 1.过滤selectFiles得到需要上传的文件
      // 删除selectFiles里面重复文件
      let deleteIndex = []
      for (let element of this.selectFiles) {
        this.selectFiles.forEach((item, index) => {
          if (item.identifier === element.identifier && item.id !== element.id && item.id <= 0) {
            deleteIndex = [index, ...deleteIndex]
            isExistSame = true
          }
        })
      }
      for (let index = 0; index < deleteIndex.length; index++) {
        this.selectFiles.splice(deleteIndex[index], 1)
      }
      // 选择的文件中删除已上传完成的
      deleteIndex = []
      this.selectFiles.forEach((element, index) => {
        this.datas.forEach(item => {
          if (item.identifier === element.identifier && item.id !== element.id && item.uploadstate !== fileStatus.md5 && item.uploadstate !== fileStatus.uploading) {
            deleteIndex = [index, ...deleteIndex]
          }
        })
      })
      for (let index = 0; index < deleteIndex.length; index++) {
        let dataIndex = this.datas.findIndex(item => {
          return item.identifier === this.selectFiles[deleteIndex[index]].identifier && item.id === this.selectFiles[deleteIndex[index]].id
        })
        if (dataIndex >= 0) {
          this.datas.splice(dataIndex, 1)
        }
        this.selectFiles.splice(deleteIndex[index], 1)
      }
      // 2.删除显示列表里面重复文件
      deleteIndex = []
      this.datas.forEach(item => {
        this.selectFiles.forEach((element, index) => {
          if (item.identifier === element.identifier && item.id !== element.id && (item.uploadstate === fileStatus.md5 || item.uploadstate === fileStatus.uploading)) {
            deleteIndex = [index, ...deleteIndex]
            if (item.id > 0) {
              element.blocksize = item.blocksize
              element.progress = item.progress
              element.uploadusername = item.uploadusername
              element.uploadstate = item.uploadstate
            }
          }
        })
      })
      // 显示界面删除已有文件
      deleteIndex.forEach((item, index) => {
        this.datas.splice(item, 1)
      })
    },
    /** 添加到上传队列中 */
    addUploadList(element) {
      let index = this.uploadFiles.findIndex(item => item.identifier === element.identifier)
      if (index === -1) {
        // 进行文件分片,添加到上传队列中
        const fileBlockList = this.createFileBlockList(element.fileObject, element.blocksize)
        element.blockList = fileBlockList.map((block, index) => ({
          filemd5: element.filemd5,
          identifier: element.filemd5,
          filename: element.name,
          blocknum: index + 1,
          blockdata: block.file
        }))
        this.uploadFiles.push(element)
        this.doUploadFileBlocks(element)
        return true
      } else {
        return false
      }
    },
    /** 创建文件分块*/
    createFileBlockList(file, blocksize) {
      const fileBlockList = []
      const blockCount = Math.ceil(file.size / blocksize)
      let currentPos = 0
      while (currentPos < file.size) {
        if (currentPos + blocksize < file.size) {
          fileBlockList.push({ file: file.slice(currentPos, currentPos + blocksize) })
        } else {
          fileBlockList.push({ file: file.slice(currentPos) })
        }
        currentPos += blocksize
      }
      return fileBlockList
    },
    /** 上传切片 */
    async doUploadFileBlocks(file) {
      var blockList = file.blockList
      const requestList = blockList.map(block => {
        const formData = new FormData()
        formData.append('file', block.blockdata)
        formData.append('blocknum', block.blocknum)
        formData.append('filename', block.filename)
        formData.append('filemd5', file.filemd5)
        formData.append('identifier', file.filemd5)
        formData.append('totalblockcount', blockList.length)
        formData.append('filesize', file.filesize)
        formData.append('blocksize', file.blocksize)
        formData.append('sourceid', this.sourceId)
        formData.append('sourcetype', this.sourceType)
        formData.append('type', this.getFileExt(block.filename))
        return formData
      })
      // 上传中
      this.formatFileState(file, fileStatus.uploading)
      // 检查是否都上传
      if (!this.checkIsAllUpload(requestList, file)) {
        await this.sendUploadRequest(requestList, file)
          .then(isContinue => {
            if (isContinue === 1) {
              // 所有上传完成合并切片
              this.formatFileState(file, fileStatus.uploadFinish)
              this.doMergeBlocksRequest(file)
            }
          })
          .catch(err => {
            // console.log("aaaaaaaaaaaaaaaa")
            // 上传块
            let index = this.uploadFiles.findIndex(element => {
              return element === file
            })
            if (index >= 0) {
              this.uploadFiles.splice(index, 1)
            }
          })
      } else {
        this.formatFileState(file, fileStatus.uploadFinish)
        this.doMergeBlocksRequest(file)
      }
    },
    /** 检查文件是否都已上传 */
    checkIsAllUpload(requestList, file) {
      let isAllUpload = true
      requestList.forEach((formData, index) => {
        // 判断块是否上传
        var i = file.alreadyuploadblocksnum.indexOf(parseInt(formData.get('blocknum')))
        if (i === -1) {
          isAllUpload = false
          return
        }
      })
      return isAllUpload
    },
    /** 发送块上传*/
    sendUploadRequest(requestList, file) {
      let promise = new Promise(async(success, fail) => {
        for (let formData of requestList) {
          // 判断块是否上传(没有在上传编码中并且文件没有终止)
          var i = file.alreadyuploadblocksnum.indexOf(parseInt(formData.get('blocknum')))
          if (i === -1 && file.uploadstate !== fileStatus.delete) {
            // 当前块没有上传提交到后台
            await postAction(this.url.uploadFileBlock, formData).then(res => {
              if (res.success) {
                let element = this.datas.find(item => {
                  return item.identifier === file.identifier && item.sourceid === file.sourceid && item.sourcetype === file.sourcetype
                })
                let id = res.result.id
                if (typeof id !== 'undefined') {
                  if (typeof element !== 'undefined') {
                    element.id = id
                    element.recordtime = res.result.recordtime
                    element.uploadusername = res.result.username
                  }
                }
                // 已上传的块记录，便于后续断点续传
                if (typeof res.result.alreadyuploadblocksnum !== 'undefined') {
                  file.alreadyuploadblocksnum = res.result.alreadyuploadblocksnum
                }
                if (file.alreadyuploadblocksnum.length === requestList.length) {
                  this.updateProgressHandler(file, formData.get('blocknum'))
                  success(1)
                } else {
                  // 更新进度条
                  this.updateProgressHandler(file, formData.get('blocknum'))
                }
              } else {
                this.$tap.alert(res.message, 'warning')
                fail()
              }
            })
          } else {
          }
        }
      })
      return promise
    },
    /** 发送合并切片 */
    async doMergeBlocksRequest(file) {
      const formData = {}
      formData.name = file.filename
      formData.filemd5 = file.filemd5
      formData.identifier = file.identifier
      formData.filesize = file.filesize
      formData.totalblockcount = file.blockList.length
      formData.sourcetype = this.sourceType
      formData.sourceid = this.sourceId
      await postAction(this.url.mergeFileBlocks, formData).then(res => {
        if (res.success) {
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    /** 更新进度条 */
    updateProgressHandler(file, blocknum) {
      if (file.alreadyuploadblocksnum.indexOf(blocknum) === -1) {
        file.alreadyuploadblocksnum.push(parseInt(blocknum))
      }
      // console.log(this.datas)
      let element = this.datas.find(item => {
        return item.identifier === file.identifier && item.sourceid === file.sourceid && item.sourcetype === file.sourcetype
      })
      // console.log(element)
      let progress = parseInt((file.alreadyuploadblocksnum.length / file.blockList.length) * 100)
      if (typeof element !== 'undefined') {
        element.progress = progress > 100 ? 100 : progress
      }
    },
    /** 计算md5，实现断点续传及秒传,注意md5计算也是分片，避免浏览器加载过大*/
    computeMD5(fileObject) {
      return new Promise((re, rj) => {
        let fileReader = new FileReader()
        let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice
        let currentBlock = 0
        let chunks = Math.ceil(fileObject.size / BLOCK_SIZE)
        let spark = new SparkMD5.ArrayBuffer()
        loadNext()
        fileReader.onload = e => {
          spark.append(e.target.result)
          if (currentBlock < chunks) {
            currentBlock++
            loadNext()
          } else {
            var filemd5 = spark.end()
            re(filemd5)
          }
        }
        fileReader.onerror = function() {
          this.error(`文件${fileObject.name}读取出错，请检查该文件`)
          rj()
        }
        function loadNext() {
          let start = currentBlock * BLOCK_SIZE
          let end = start + BLOCK_SIZE >= fileObject.size ? fileObject.size : start + BLOCK_SIZE
          fileReader.readAsArrayBuffer(blobSlice.call(fileObject, start, end))
        }
      })
    },
    /** 上传单个文件 */
    uploadSignleFile(options) {
      var file = options.file
      var signleUploadRow = options.data
      this.checkSignleUpload(file, signleUploadRow)
        .then(_ => {
          // 请求服务端得到没有上传的块
          signleUploadRow.filemd5 = signleUploadRow.identifier
          this.queryUploadBlocksNum(signleUploadRow.identifier).then(alreadyUploadBlocksMap => {
            // 进行文件分片
            var alreadyUploadBlocksnum = alreadyUploadBlocksMap[signleUploadRow.identifier]
            if (typeof alreadyUploadBlocksnum === 'undefined') {
              alreadyUploadBlocksnum = []
            }
            signleUploadRow.alreadyuploadblocksnum = alreadyUploadBlocksnum
            const fileBlockList = this.createFileBlockList(file, signleUploadRow.blocksize)
            signleUploadRow.filename = file.name
            signleUploadRow.blockList = fileBlockList.map((block, index) => ({
              filename: file.name,
              blocknum: index + 1,
              blockdata: block.file
            }))
            // 执行文件上传
            this.doUploadFileBlocks(signleUploadRow)
          })
        })
        .catch(err => {
          // console.log('aaaaa')
          return false
        })
    },
    /** 单个选择上传 */
    checkSignleUpload(file, signleUploadRow) {
      return new Promise((success, fail) => {
        if (this.limitType) {
          let fileType = this.getFileExt(file.name)
          let isRight = true
          for (let type of this.limitType.split(';')) {
            if (type.toLowerCase().indexOf(fileType.toLowerCase()) === -1) {
              isRight = false
              break
            }
          }
          if (!isRight) {
            this.$tap.alert(`上传文件只能是 ${this.limitType}格式!`, 'warning')
            fail()
            return
          }
        }
        if (signleUploadRow.uploadState === fileStatus.finish) {
          this.$tap.alert(`已上传`, 'warning')
          fail()
          return
        }
        // 检查文件是否一致
        if (signleUploadRow.identifier.length > 0) {
          // 计算选择文件md5
          this.computeMD5(file).then(md5 => {
            if (signleUploadRow.identifier !== md5) {
              this.$tap.alert(`不是同一个文件，请重新选择文件`, 'warning')
              fail()
              return
            } else {
              success()
            }
          })
        }
      })
    },
    /** 查询已经上传的块号 */
    queryUploadBlocksNum(identifier) {
      return new Promise((success, fail) => {
        const formData = {}
        formData.qry_identifiers = identifier
        formData.qry_sourceid = this.sourceId
        formData.qry_sourcetype = this.sourceType
        getAction(this.url.queryAlreadyUploadBlocksNum, formData).then(res => {
          if (res.success) {
            success(res.result)
          } else {
            fail()
          }
        })
      })
    },
    /** 播放（音频、视频） */
    doPlay(id) {
      if (typeof id === 'undefined') {
        this.$tap.alert('没有完成，无法播放', 'warning')
        return
      }
      return getAction(this.url.load, { id: id }).then(res => {
        if (res.success) {
          if (res.result.uploadstate === fileStatus.uploading) {
            this.$tap.alert('文件没有上传完成，请继续上传', 'warning')
            return
          }
          if (res.result.uploadstate !== fileStatus.finish) {
            this.$tap.alert('文件安全处理中', 'warning')
            return
          }
          this.audioName = '播放 ' + res.result.name
          // var playSrc = {}
          // // playSrc.sourceSrc = process.env.BASE_API + '/play/audio/' + res.result.location
          // playSrc.sourceSrc = process.env.BASE_API + this.url.m3u8Url + '?qry_identifier=' + res.result.identifier
          // playSrc.sourceType = 'application/x-mpegURL'
          // if (res.result.type !== null && res.result.type.toLowerCase() === 'mp4') {
          //   this.playVideoVisible = true
          //   this.$nextTick(() => {
          //     this.$refs.playVideoForm.playSource(playSrc)
          //   })
          // } else {
          //   this.playAudioVisible = true
          //   this.$nextTick(() => {
          //     this.$refs.playAudioForm.playSource(playSrc)
          //   })
          // }
          // 请求加密 blob http路径
          axios({
            url: this.url.getBlobSrc,
            method: 'post',
            data: { qry_location: res.result.location },
            responseType: 'blob' // arraybuffer
          }).then(response => {
            let url = URL.createObjectURL(response)
            var playSrc = {}
            playSrc.sourceSrc = url // process.env.BASE_API + '/play/audio/' + res.result.location
            playSrc.sourceType = 'application/x-mpegURL'
            if (res.result.type.toLowerCase() === 'mp4') {
              this.playVideoVisible = true
              this.$nextTick(() => {
                this.$refs.playVideoForm.playSource(playSrc)
              })
            } else {
              this.playAudioVisible = true
              this.$nextTick(() => {
                this.$refs.playAudioForm.playSource(playSrc)
              })
            }
          })
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    /** 删除 */
    doDelete(scope) {
      this.$tap
        .confirm('确定删除数据吗？')
        .then(_ => {
          let id = scope.row.id
          // console.log(scope)
          // 本地删除
          if (id <= 0) {
            this.datas.splice(scope.$index, 1)
            let index = this.selectFiles.findIndex(item => {
              return item === this.datas[scope.$index]
            })
            if (index >= 0) {
              this.uploadFiles[index].uploadstate = fileStatus.delete
              this.uploadFiles.splice(index, 1)
            }
            return
          }
          deleteAction(this.url.delete, { ids: scope.row.id }).then(res => {
            if (res.success) {
              this.$tap.message(res.message, 'success')
              // 删除应该终止上传
              for (let index = 0; index < this.uploadFiles.length; index++) {
                if (this.uploadFiles[index].id === scope.row.id) {
                  // 终止
                  this.uploadFiles[index].uploadstate = fileStatus.delete
                  this.uploadFiles.splice(index, 1)
                  break
                }
              }
              this.loadData()
            } else {
              this.$tap.alert(res.message, 'warning')
            }
          })
        })
        .catch(_ => {})
    },
    /** 关闭音频 */
    playClose(type) {
      if (type === fileType.audio) {
        this.$refs.playAudioForm.stopPlay()
      } else if (type === fileType.video) {
        this.$refs.playVideoForm.stopPlay()
      }
    },
    /** 表格大小格式化 */
    formatFileSize(row, column, cellValue, index) {
      let size = row[column.property]
      var fileSize = 0
      var len
      if (size / 1024 > 1024) {
        len = size / 1024 / 1024
        fileSize = len.toFixed(2) + 'MB'
      } else if (size / 1024 / 1024 > 1024) {
        len = size / 1024 / 1024 / 1024
        fileSize = len.toFixed(2) + 'GB'
      } else {
        len = size / 1024
        fileSize = len.toFixed(2) + 'KB'
      }
      return fileSize
    },
    /** 格式化文件状态 */
    formatFileState(file, status) {
      var dispStatus = fileStatusStr[fileStatus[status]]
      file.dispuploadstate = dispStatus
      file.uploadstate = status
    },
    /** 文件扩展名 */
    getFileExt(fileName) {
      let arr = fileName.split('.')
      if (arr.length === 0) {
        return ''
      } else {
        return arr[arr.length - 1].toString().toLowerCase()
      }
    },
    /** 清空文件选择 */
    clearFileInput() {
      document.getElementById('fileInput').value = ''
    },
    /** 加载后初始化对比 */
    afterLoadData() {
      // 如果新打开编辑界面，则需要清空原来uploadFiles
      if (this.sourceId !== this.oldSourceId) {
        // 所有文件状态设置停止上传
        for (let file of this.uploadFiles) {
          file.uploadstate = fileStatus.delete
        }
        this.uploadFiles = []
        this.selectFiles = []
        this.oldSourceId = this.sourceId
      } else {
        // 正在上传的与新加载列表数据对比，进行显示初始化
        for (let selectFile of this.selectFiles) {
          if (typeof selectFile.identifier === 'undefined') {
            this.datas.push(selectFile)
          } else {
            let isExist = false
            for (let data of this.datas) {
              if (data.identifier === selectFile.identifier) {
                data = selectFile
                isExist = true
                break
              }
            }
            if (isExist === false) {
              this.datas.push(selectFile)
            }
          }
        }
      }
    }
  }
}
</script>
<style>
.btns {
  margin-bottom: 10px;
}
.select-file-button {
  height: 36px;
}
.select-file-input {
  position: relative;
  top: -4px;
}
/* .tl-dialog .el-dialog .el-dialog__header {
  background-color: #000;
}
.tl-dialog .el-dialog .el-dialog__body {
  background-color: #000;
}
.video-js .vjs-control-bar {
  margin-bottom: 11px;
} */
</style>
